package fr.lip6.meta.tools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.eclipse.emf.common.util.TreeIterator;
//import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.resource.UML212UMLResource;
import org.eclipse.uml2.uml.resource.UMLResource;

import java.util.*;

/**
 * 
 * Cette classe charge un "Model" depuis un fichier XMI
 *
 */
public class UMLLoader {
	protected static UMLLoader instance;
	private UMLLoader(){
	}
	
	public static UMLLoader getInstance(){
		if(instance == null){
			instance = new UMLLoader();
		}
		return instance;
	}
	
	public List<EObject> loadUMLFromFile(File file) throws IOException{
		return loadUMLFromURI(org.eclipse.emf.common.util.URI.createFileURI(file.getAbsolutePath()));
	}
	
	public List<EObject> loadUMLFromURI(org.eclipse.emf.common.util.URI uri) throws IOException {
		ResourceSet resourceSet = new ResourceSetImpl();
		resourceSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
		resourceSet.getPackageRegistry().put(UML212UMLResource.UML_METAMODEL_NS_URI, UMLPackage.eINSTANCE);
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
		Resource model = resourceSet.getResource(uri, true);
	
		
		TreeIterator<EObject> contents = model.getAllContents();
		List<EObject> res = new ArrayList<EObject>();
		while(contents.hasNext()){
			EObject o  = contents.next();
			res.add(o);
		}
		return res;
	}
}
